import 'dart:io';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_app2/main1.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

/// sqlite存储数据
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    saveDb();
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text("fluter123"),
        ),
        body: Text("123456"),
      ),
    );
  }
}

Future<void> saveDb() async {
  WidgetsFlutterBinding.ensureInitialized();
  final dataBase =
      openDatabase(join(await getDatabasesPath(), 'doggie_database.db'),
          onCreate: (db, version) {
    return db.execute(
        'CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
  }, version: 1);

  Future<void> insertDog(Dog dog) async {
    final db = await dataBase;
    await db.insert('dogs', dog.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  Future<List<Dog>> dogs() async {
    final db = await dataBase;
    final List<Map<String, dynamic>> maps = await db.query('dogs');
    return List.generate(
        maps.length,
        (index) => Dog(
            id: maps[index]['id'],
            name: maps[index]['name'],
            age: maps[index]['age']));
  }

  Future<void> updateDogs(Dog dog) async {
    final db = await dataBase;
    db.update(
      'dogs',
      dog.toMap(),
      where: 'id=?',
      whereArgs: [dog.id],
    );
  }

  Future<void> deleteDogs(int id) async {
    final db = await dataBase;
    db.delete('dogs', where: 'id=?', whereArgs: [id]);
  }

  var fido = Dog(id: 0, name: "fido", age: 10);
  await insertDog(fido);

  print("db_dogs   ${await dogs()}");
  // return await dogs();

  var fido1 = Dog(id: fido.id, name: fido.name, age: fido.age + 7);
  await updateDogs(fido1);
  print("fid01   ${await dogs()}");


  deleteDogs(fido1.id);
  print("fid02   ${await dogs()}");
}

class Dog {
  final int id;
  final String name;
  final int age;

  Dog({
    required this.id,
    required this.name,
    required this.age,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }

  @override
  String toString() {
    return 'Dog{id: $id, name: $name, age: $age}';
  }
}
